<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>系统管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片式图 -->
		<el-card class="box-card">
			<!-- 搜索添加区 -->

			<el-row :gutter="20">
				<el-col :span="8" label="用户名">
					<!-- @clear 绑定getuserlist 点击文本清除时重新搜索数据 -->

					<el-input @clear="getuserlist" clearable placeholder="请输入用户名称" v-model="formInline.loginName" class="input-with-select"></el-input>
				</el-col>
				<el-col :span="8">
					<el-select v-model="formInline.isLockout" placeholder="请选择账号状态">
						<el-option label="全部"></el-option>
						<el-option label="是" value="1"></el-option>
						<el-option label="否" value="0"></el-option>
					</el-select>
					<el-button type="success" @click="getuserlist">搜索</el-button>
				</el-col>
				<el-col :span="4"><el-button type="primary" @click="addDialogVisible = true">添加用户</el-button></el-col>
			</el-row>

			<!-- 用户列表区 -->
			<el-table :data="userlist" border stripe style="width: 100%">
				<el-table-column prop="uid" label="编号" width="70"></el-table-column>
				<el-table-column prop="loginName" label="登录名" width="180"></el-table-column>
				<el-table-column prop="email" label="邮箱"></el-table-column>
				<el-table-column prop="phone" label="手机号"></el-table-column>
				<el-table-column prop="createTime" label="创建时间"></el-table-column>
				<el-table-column prop="isLockout" label="是否锁定">
					<template slot-scope="scope">
						<el-tooltip content="绿:锁定 红:未锁定" placement="top">
							<el-switch
								v-model="scope.row.isLockout"
								active-color="#13ce66"
								inactive-color="#ff4949"
								@change="changeStatus(scope.row)"
								:active-value="1"
								:inactive-value="0"
							></el-switch>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column prop="lockTime" label="锁定时间"></el-table-column>
				<el-table-column label="操作" width="300">
					<template slot-scope="scope">
						<el-button type="success" size="mini" v-on:click="setRole(scope.row.uid)">角色</el-button>
						<el-button type="warning" size="mini" v-on:click="showEditDialog(scope.row)">编辑</el-button>
						<el-button type="warning" size="mini" v-on:click="removeUserById(scope.row.uid)">删除</el-button>
						<el-button type="primary" size="mini" v-on:click="resetdata(scope.row.uid)">重置</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页区 -->
			<el-pagination
				v-on:size-change="handleSizeChange"
				v-on:current-change="handleCurrentChange"
				:current-page="page"
				:page-sizes="[5, 10, 15]"
				:page-size="100"
				layout="total, sizes, prev, pager, next, jumper"
				:total="count"
			></el-pagination>
		</el-card>
		<!-- 添加用户的对话框 -->
		<el-dialog title="添加用户:" v-on:close="addDialogclosed" :visible.sync="addDialogVisible" width="50%">
			<!-- 内容主体区域 -->

			<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
				<el-form-item label="用户名称" prop="loginName"><el-input v-model="addForm.loginName"></el-input></el-form-item>
				<el-form-item label="邮箱" prop="email"><el-input v-model="addForm.email"></el-input></el-form-item>
				<el-form-item label="电话" prop="phone"><el-input v-model="addForm.phone"></el-input></el-form-item>
			</el-form>

			<!-- 底部区域 -->
			<span slot="footer" class="dialog-footer">
				<el-button v-on:click="addDialogVisible = false">取 消</el-button>
				<el-button type="primary" v-on:click="addUser()">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 修改用户的对话框 -->
		<el-dialog title="修改用户" @close="editDialogclosed" :visible.sync="editDialogVisible" width="50%">
			<el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="70px">
				<el-form-item label="用户名"><el-input disabled v-model="editForm.loginName"></el-input></el-form-item>
				<el-form-item label="邮箱" prop="email"><el-input v-model="editForm.email"></el-input></el-form-item>
				<el-form-item label="手机号" prop="phone"><el-input v-model="editForm.phone"></el-input></el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="edituserinfo">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 分配角色的对话框 -->
		<el-dialog title="分配角色" :visible.sync="setRoledialogVisible" width="50%" @close="setRoleDialogClosed">
			<el-transfer v-model="yesData" :props="{ key: 'rid', label: 'rname' }" :titles="['所有角色', '拥有角色']" @change="handleChange" :data="noData"></el-transfer>

			<span slot="footer" class="dialog-footer">
				<el-button @click="setRoledialogVisible = false">关闭</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
	data() {
		// 验证邮箱的规则
		var checkEmail = (rule, value, cb) => {
			//验证邮箱的正则表达式
			const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

			if (regEmail.test(value)) {
				//合法的邮箱
				return cb();
			}
			cb(new Error('请输入合法的邮箱'));
		};

		//验证手机号的规则
		var checkMobile = (rule, value, cb) => {
			//验证手机号的正则
			const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
			if (regMobile.test(value)) {
				return cb();
			}
			cb(new Error('请输入合法的手机号'));
		};
		return {
			noData: [],
			yesData: [],
			//获取用户列表参数对象
			formInline: {
				isLockout: '',
				loginName: ''
			},
			page: 1,
			limit: 5,
			count: 0,
			switchrow: {},
			//添加用户的表单数据
			addForm: {
				username: '',
				password: '',
				email: '',
				mobile: ''
			},
			//添加用户表单验证的验证规则对象
			addFormRules: {
				loginName: [
					{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					},
					{
						min: 3,
						max: 10,
						message: '用户名的长度在3~10之间',
						trigger: 'blur'
					}
				],
				password: [
					{
						required: true,
						message: '密码',
						trigger: 'blur'
					},
					{
						min: 6,
						max: 15,
						message: '密码的长度在6~15之间',
						trigger: 'blur'
					}
				],
				email: [
					{
						required: true,
						message: '请输入邮箱',
						trigger: 'blur'
					},
					{
						validator: checkEmail,
						trigger: 'blur'
					}
				],
				phone: [
					{
						required: true,
						message: '请输入手机号',
						trigger: 'blur'
					},
					{
						validator: checkMobile,
						trigger: 'blur'
					}
				]
			},
			//编辑用户表单验证对象
			editFormrules: {
				email: [
					{
						required: true,
						message: '请输入邮箱',
						trigger: 'blur'
					},
					{
						validator: checkEmail,
						trigger: 'blur'
					}
				],
				phone: [
					{
						required: true,
						message: '请输入手机号',
						trigger: 'blur'
					},
					{
						validator: checkMobile,
						trigger: 'blur'
					}
				]
			},
			// 存放用户列表数据
			userlist: [],
			//数据总条数
			total: 0,
			//控制添加用户对话框的显示和隐藏
			addDialogVisible: false,
			//控制修改对话框的显示和隐藏
			editDialogVisible: false,
			//用户查询到的用户信息对象
			editForm: {},
			//控制分配角色对话框的显示与隐藏
			setRoledialogVisible: false,
			//需要被分配角色的用户信息
			userinfo: {},
			//角色列表
			roleslist: [],
			//存放选中下拉列表中的值
			selectedRoleId: '',
			str: '',
			uid:''
		};
	},
	created() {
		this.getuserlist();
	},
	methods: {
		async getuserlist() {
			const { data: res } = await this.$http.get('api/user/getnumbertable', {
				params: {
					page: this.page,
					limit: this.limit,
					loginName: this.formInline.loginName,
					isLockout: this.formInline.isLockout
				}
			});
			if (res.code !== 0) return this.$message.error('获取用户数据失败');
			this.userlist = res.data;
			this.count = res.count;
		},
		//监听pagesize改变的事件
		handleSizeChange(newSize) {
			this.limit = newSize;
			this.getuserlist();
		},
		//监听页面值改变的事件
		handleCurrentChange(newPage) {
			this.page = newPage;
			this.getuserlist();
		},
		//修改用户信息事件
		async userStateChanged(userinfo) {
			const { data: res } = await this.$http.put(`users/${userinfo.id}
			/state/${userinfo.mg_state}`);
			if (res.meta.status != 200) {
				userinfo.mg_state = !userinfo.mg_state;
				return this.$message.error(res.meta.msg);
			} else {
				return this.$message.success(res.meta.msg);
			}
		},
		//监听添加用户对话框的关闭事件清除input内容
		addDialogclosed() {
			this.$refs.addFormRef.resetFields();
		},
		//点击按钮添加新用户
		addUser() {
			this.$refs.addFormRef.validate(async valid => {
				if (!valid) return;
				//可以发起用户请求
				const { data: res } = await this.$http.post('api/user/adduser', this.addForm);
				if (res.code != 0) {
					this.$message.success(res.msg);
				}
				this.$message.success(res.msg);

				//隐藏添加用户的对话框
				this.addDialogVisible = false;

				//重新获取用户列表数据
				this.getuserlist();
			});
		},
		//展示编辑用户对话框
		showEditDialog(row) {
			this.editForm = row;
			this.editDialogVisible = true;
		},
		//监听用户修改对话框的关闭事件重置input框
		editDialogclosed() {
			this.$refs.editFormRef.resetFields();
		},
		//修改用户信息并提交
		edituserinfo() {
			this.$refs.editFormRef.validate(async valid => {
				if (!valid) return;
				const { data: res } = await this.$http.post('api/user/edituser', this.editForm);
				if (res.code != 0) {
					return this.$message.error('查询用户数据失败');
				}
				//提示成功
				this.$message.success('更新成功');
				//关闭对话框
				this.editDialogVisible = false;
				//刷新列表
				this.getuserlist();
			});
		},

		async resetdata(uid) {
			const confirmResult = await this.$confirm('此操作将重置用户, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				//如果用户取消删除则 则打印cancel字符串
				.catch(err => err);
			//如果用户确认删除则confirmResult 为confim字符串

			if (confirmResult != 'confirm') {
				return this.$message.info('已经取消重置');
			}
			const { data: res } = await this.$http.post('api/user/resetuser', {
				uid: uid
			});
			if (res.code != 0) {
				this.$message.error('重置失败' + res.msg);
			}
			this.$message.success('重置成功');
			this.getuserlist();
		},

		//移除用户事件
		async removeUserById(uid) {
			const confirmResult = await this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				//如果用户取消删除则 则打印cancel字符串
				.catch(err => err);
			//如果用户确认删除则confirmResult 为confim字符串

			if (confirmResult != 'confirm') {
				return this.$message.info('已经取消删除');
			}
			const { data: res } = await this.$http.post('api/user/del', {
				uid: uid
			});
			if (res.code != 0) {
				this.$message.error('删除失败' + res.msg);
			}
			this.$message.success('删除成功');
			this.getuserlist();
		},
		//switch开关事件
		async changeStatus(row) {
			this.switchrow = row;
			const { data: res } = await this.$http.post('api/user/updatestatus', this.switchrow);
			if (res.code != 0) {
				this.$message.error(res.msg);
			}
			this.$message.success(res.msg);
			this.getuserlist();
		},
	async	getuserrole(uid){
			//展示对话框之前获取所有用户角色列表
			const { data: res } = await this.$http.get('api/user/getrolelist', {
				params: {
					uid: uid
				}
			});
			if (res.code != 0) return this.$message.error('获取数据失败');
			this.noData = res.data1;
			this.yesData = res.data2;
		},
		 setRole(uid) {
			this.uid=uid;
           this.getuserrole(uid)
			this.setRoledialogVisible = true;
		},
	async	handleChange(value, direction, movedKeys) {
			//可以通过direction回调right/left 来进行操作，right：把数字移到右边，left把数据移到左边
			if (direction === 'right') {
				for (var i = 0; i < value.length; i++) {
					this.str += value[i] + ',';
				}
				const{data:res} =await this.$http.post('api/user/add', {
						str:this.str.substring(0,this.str.length-1),
						userid:parseInt(this.uid)
					})
					console.log(res)
						
						if (res.code == 0) {
							this.$message.success('更改成功');
							this.getuserrole(this.uid);
							this.str=""
						} else {
							this.$message.error('更改失败');
						}
					
					
			}
			if (direction === 'left') {
				
			for (var i = 0; i < movedKeys.length; i++) {
				this.str += movedKeys[i] + ',';
			}
			const{data:res} =await	this.$http.post('api/user/dele', {
					str:this.str.substring(0,this.str.length-1),
					userid:parseInt(this.uid)
				})
					if (res.code == 0) {
						this.$message.success('更改成功');
						this.getuserrole(this.uid);
						this.str=""
					} else {
						this.$message.error('更改失败');
					}
			}
		}
	
	}
};
</script>

<style lang="less" scoped></style>
